package com.example.coder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * RpcRequest 解码器
 */
public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;
    private Serializer serializer;


    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;

    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (byteBuf.readableBytes() < Integer.BYTES) {
            return;
        }
        // 获取消息长度
        int byteLen = byteBuf.readInt();
        // 消息内容
        byte[] content = new byte[byteLen];
        // 将数据读入 byte 数组
        byteBuf.readBytes(content);
        Object o = serializer.deserialize(clazz, content);
        list.add(o);
    }
}
